/**
 * 
 */
package mobi.ilabs.restroom;

import mobi.ilabs.EILog;
import mobi.ilabs.restroom.storage.Storage;

import org.apache.commons.logging.Log;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;

public class FileStore extends Restlet {
    
    private final Storage mStorage;
    
    /**
     * The log to use when we are griping.
     */
    private static  Log LOG = 
        EILog.getLog(FileStore.class);

    final ObStoreRestlet innerObstore;
    
    public FileStore(Context c, Storage m, ObStoreRestlet ios) {
        super(c);
        innerObstore = ios;
        mStorage = m;
        
    }
    
    @Override
    public void handle(
            final Request  request,
            final Response response) {
        final Method method       = request.getMethod();
        final Reference resource  = request.getResourceRef();
        //  final String relativePart = resource.getRelativePart();
        final String relativePart = resource.getRemainingPart();

        if (method.equals(Method.GET)) {
            // Get the object ID, delegate to object get (which then
            // holds all the ACL stuff for getting stuff)

            LOG.debug("handling GET in filestore, before getting the OBID");
            final String obid = mStorage.getObidFromFilename(request, relativePart);
            LOG.debug("handling GET in filestore, just got the obid(" + obid + ")");

            if (obid == null) {
                response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            } else {
                ObStoreRestlet.putRequestObid(request, obid);
                innerObstore.handle(request, response);
            }
        } else if (method.equals(Method.PUT)
                || method.equals(Method.POST)) {
            ObStoreRestlet.putRequestFilename(request, relativePart);
            innerObstore.handle(request, response);
        } else {
            response.setEntity("Illegal method", MediaType.TEXT_PLAIN);
            response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
        }
    }
    
}